package cas.server.login;

import cas.client.User;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;


@WebServlet(name = "LoginPageServlet", urlPatterns = "/login-page")
public class LoginPageServlet extends HttpServlet {

    private static final String DEFAULT_RETURN_ADDRESS = "/";
    private static final String CAS_NAME = "http://localhost:8080";

    // 登录页面
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 跳转返回地址
        String returnAddress;
        if (request.getParameter("return-address") == null) {
            returnAddress = DEFAULT_RETURN_ADDRESS;
        } else {
            returnAddress = request.getParameter("return-address");
        }
        // 先看看cookie中有没有token
        String tokenInCookie = getTokenFromCookies(request.getCookies());
        if (tokenInCookie != null) {
            // cookie中有token
            try {
                User user = requestCAS(tokenInCookie);
                if (user != null) {
                    // cookie中的token有效，无需再次登录
                    if(returnAddress.contains("?")) {
                        response.sendRedirect(URLDecoder.decode(returnAddress, "UTF-8") + "&token=" + tokenInCookie);
                    } else {
                        response.sendRedirect(URLDecoder.decode(returnAddress, "UTF-8") + "?token=" + tokenInCookie);
                    }
                    return;
                }
            } catch (IOException ignored) {

            }
        }
        // 跳转到登录页面
        request.getSession().setAttribute("returnAddress", returnAddress);
        RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/jsp/LoginPage.jsp");
        dispatcher.forward(request, response);
    }

    // 得到Cookies中的token
    private static String getTokenFromCookies(Cookie[] cookies) {
        if (cookies == null)
            return null;
        Cookie token = null;
        for (Cookie cookie: cookies) {
            if (cookie.getName().equals("token")) {
                token = cookie;
                break;
            }
        }
        if (token == null) {
            return null;
        } else {
            return token.getValue();
        }
    }

    // 向CAS发送请求，验证token
    private static User requestCAS(String token) throws IOException {
        URL url = new URL(CAS_NAME + "/user-info-api");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Accept", "application/json");
        conn.setRequestProperty("Accept-Charset", "UTF-8");
        conn.setRequestProperty("Authorization", token);
        ObjectMapper objectMapper = new ObjectMapper();
        User user = objectMapper.readValue(conn.getInputStream(), User.class);
        conn.disconnect();
        return user;
    }

}
